package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.UserLocation;
import com.tanhua.dubbo.api.mongo.UserLocationApi;
import com.tanhua.vo.LocationManagerVo;
import com.tanhua.vo.PageResult;
import com.tanhua.vo.UserLocationVo;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metric;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.*;

@Service
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void saveLocation(Long userId, Double longitude, Double latitude, String addrStr) {

//        1、先根据userId查询是否有UserLocation
        Query query = new Query(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
//                如果有就是修改
        if(userLocation!=null){

            Update update = new Update();
            update.set("lastUpdated",new Date().getTime());
            update.set("updated",new Date().getTime());
            update.set("address",addrStr);
            update.set("location",new GeoJsonPoint(longitude,latitude));
            mongoTemplate.updateFirst(query,update,UserLocation.class);

        }else{ //  如果没有就是新增
            userLocation = new UserLocation();
            userLocation.setId(new ObjectId());
            userLocation.setUserId(userId);
            userLocation.setLocation(new GeoJsonPoint(longitude,latitude));
            userLocation.setAddress(addrStr);
            userLocation.setCreated(new Date().getTime());
            userLocation.setUpdated(new Date().getTime());
            userLocation.setLastUpdated(new Date().getTime());
            mongoTemplate.save(userLocation);
        }
//

    }

    @Override
    public List<UserLocationVo> search(Long userId, Integer distance) {
        Query query = new Query(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        GeoJsonPoint geoJsonPoint = userLocation.getLocation();
//        以当前登录人的位置为圆心，以distance为半径 画一个圆
        Circle circle = new Circle(geoJsonPoint, new Distance(distance/1000 , Metrics.KILOMETERS));
        Query query1 = new Query(Criteria.where("location").withinSphere(circle));
        List<UserLocation> userLocationList = mongoTemplate.find(query1, UserLocation.class);
        List<UserLocationVo> userLocationVos = UserLocationVo.formatToList(userLocationList);
        return userLocationVos;
    }

    /*
    根据Id查询地理位置
     */
    @Override
    public Map<String,Double> queryById(Long id) {
        Query query = new Query(Criteria.where("userId").is(id));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        GeoJsonPoint location = userLocation.getLocation();
        double longitude = location.getX();
        double latitude = location.getY();
        Map<String,Double> map =new HashMap<>();
        map.put("longitude",longitude);
        map.put("latitude",latitude);
        return map;
    }

    /*
    分页查询用户位置
    by Huo
     */
    @Override
    public PageResult queryByPage(Integer page, Integer pageSize) {
        Query query = new Query().limit(pageSize).skip((long) pageSize * (page - 1));
        List<UserLocation> locations = mongoTemplate.find(query,UserLocation.class);
        long count = mongoTemplate.count(query,UserLocation.class);
        List<LocationManagerVo> list = new ArrayList<>();
        for (UserLocation location : locations) {
            LocationManagerVo locationManagerVo = new LocationManagerVo();
            locationManagerVo.setId(location.getUserId());
            locationManagerVo.setLongitude(location.getLocation().getX());
            locationManagerVo.setLatitude(location.getLocation().getY());
            list.add(locationManagerVo);
        }
        return new PageResult(page,pageSize, (int) count,list);
    }
}
